<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 页面头部 -->
    <page-header 
      title="SEO基础设置" 
      subtitle="配置网站的全局SEO信息，包括标题、关键词和描述等"
    >
      <template #extra>
        <button 
          class="btn btn-primary"
          @click="handleSave"
          :loading="saving"
        >
          <i v-if="saving" class="fa fa-spinner fa-spin mr-1"></i>
          保存设置
        </button>
      </template>
    </page-header>
    
    <!-- 主要内容区 -->
    <div class="px-4 sm:px-6 lg:px-8 py-6">
      <div class="bg-white rounded-lg shadow-md p-6 max-w-3xl mx-auto">
        <!-- SEO设置表单 -->
        <form @submit.prevent="handleSave">
          <!-- 网站标题设置 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-1">
              网站标题
              <span class="text-red-500">*</span>
            </label>
            <input
              type="text"
              v-model="seoForm.siteTitle"
              placeholder="输入网站标题"
              class="form-input w-full"
              maxlength="100"
              required
            >
            <p class="mt-1 text-xs text-gray-500">
              网站标题会显示在浏览器标签页和搜索引擎结果中，建议不超过60个字符
              <span class="ml-2 text-gray-400">{{ seoForm.siteTitle.length }}/100</span>
            </p>
          </div>
          
          <!-- 网站副标题设置 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-1">
              网站副标题
            </label>
            <input
              type="text"
              v-model="seoForm.siteSubtitle"
              placeholder="输入网站副标题（可选）"
              class="form-input w-full"
              maxlength="100"
            >
            <p class="mt-1 text-xs text-gray-500">
              副标题会跟在主标题后面，用分隔符隔开
              <span class="ml-2 text-gray-400">{{ seoForm.siteSubtitle.length }}/100</span>
            </p>
          </div>
          
          <!-- 标题分隔符 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-1">
              标题分隔符
            </label>
            <select
              v-model="seoForm.titleSeparator"
              class="form-input w-full"
            >
              <option value="|">竖线 (|)</option>
              <option value="-">横线 (-)</option>
              <option value="–">短横线 (–)</option>
              <option value="—">长横线 (—)</option>
              <option value="•">点 (•)</option>
              <option value="::">双冒号 (::)</option>
            </select>
          </div>
          
          <!-- 网站关键词 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-1">
              网站关键词
              <span class="text-red-500">*</span>
            </label>
            <textarea
              v-model="seoForm.keywords"
              placeholder="输入网站核心关键词，用逗号分隔"
              class="form-input w-full min-h-[100px]"
              maxlength="500"
              required
            ></textarea>
            <p class="mt-1 text-xs text-gray-500">
              关键词应准确描述网站内容，建议3-5个核心关键词，不超过20个
              <span class="ml-2 text-gray-400">{{ seoForm.keywords.length }}/500</span>
            </p>
          </div>
          
          <!-- 网站描述 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-1">
              网站描述
              <span class="text-red-500">*</span>
            </label>
            <textarea
              v-model="seoForm.description"
              placeholder="输入网站描述"
              class="form-input w-full min-h-[120px]"
              maxlength="300"
              required
            ></textarea>
            <p class="mt-1 text-xs text-gray-500">
              描述将显示在搜索引擎结果中，简要介绍网站内容，建议120-160个字符
              <span class="ml-2 text-gray-400">{{ seoForm.description.length }}/300</span>
            </p>
          </div>
          
          <!-- 网站作者 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-1">
              网站作者
            </label>
            <input
              type="text"
              v-model="seoForm.author"
              placeholder="输入网站作者名称（可选）"
              class="form-input w-full"
              maxlength="100"
            >
          </div>
          
          <!--  robots.txt 设置 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-1">
              robots.txt 内容
            </label>
            <textarea
              v-model="seoForm.robotsTxt"
              placeholder="User-agent: *&#10;Disallow: /admin/&#10;Allow: /"
              class="form-input w-full min-h-[150px] font-mono text-sm"
            ></textarea>
            <p class="mt-1 text-xs text-gray-500">
              配置搜索引擎爬虫的访问规则，控制哪些内容可以被索引
            </p>
          </div>
          
          <!-- 启用SEO优化 -->
          <div class="mb-4">
            <label class="inline-flex items-center">
              <input
                type="checkbox"
                v-model="seoForm.enabled"
                class="text-primary focus:ring-primary"
              >
              <span class="ml-2 text-sm font-medium text-gray-700">启用SEO优化功能</span>
            </label>
          </div>
        </form>
      </div>
      
      <!-- SEO预览卡片 -->
      <div class="bg-white rounded-lg shadow-md p-6 max-w-3xl mx-auto mt-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">搜索引擎结果预览</h3>
        <div class="border border-gray-200 rounded-md p-4 bg-gray-50">
          <div class="text-blue-600 font-medium mb-1 hover:underline">
            {{ seoForm.siteTitle || '网站标题示例' }}{{ seoForm.siteSubtitle ? `${seoForm.titleSeparator || '|'}${seoForm.siteSubtitle}` : '' }}
          </div>
          <div class="text-gray-500 text-sm mb-2">
            https://example.com/home
          </div>
          <div class="text-gray-700">
            {{ seoForm.description || '这是网站描述的示例文本，将显示在搜索引擎结果中，帮助用户了解网站内容...' }}
          </div>
        </div>
      </div>
    </div>
    
    <!-- 成功提示对话框 -->
    <FormDataDetailDialog
      :visible="showSuccessDialog"
      title="操作成功"
      :data="{ message: 'SEO设置已成功保存' }"
      :fields="[{ label: '提示信息', name: 'message', type: 'text' }]"
      @close="showSuccessDialog = false"
    />
    
    <!-- 确认对话框 -->
    <ConfirmDialog
      :visible="showDiscardConfirm"
      title="放弃更改"
      message="您有未保存的更改，确定要放弃吗？"
      @confirm="handleDiscardChanges"
      @cancel="showDiscardConfirm = false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import FormDataDetailDialog from '@/components/FormDataDetailDialog.vue'
import ConfirmDialog from '@/components/ConfirmDialog.vue'
import { useRouter } from 'vue-router'
import { getSeoSettings, saveSeoSettings } from '@/api/seo'

// 路由实例
const router = useRouter()

// 表单数据
const seoForm = reactive({
  siteTitle: '',
  siteSubtitle: '',
  titleSeparator: '|',
  keywords: '',
  description: '',
  author: '',
  robotsTxt: 'User-agent: *\nDisallow: /admin/\nAllow: /',
  enabled: true
})

// 状态变量
const saving = ref(false)
const showSuccessDialog = ref(false)
const showDiscardConfirm = ref(false)
const originalData = ref({})
const hasChanges = ref(false)

// 初始化数据
onMounted(async () => {
  try {
    const response = await getSeoSettings()
    if (response.data) {
      Object.assign(seoForm, response.data)
      // 保存原始数据用于检测变化
      originalData.value = { ...response.data }
    }
  } catch (error) {
    console.error('获取SEO设置失败:', error)
  }
})

// 监听表单变化
watch(
  () => seoForm,
  (newVal) => {
    // 比较当前数据与原始数据是否有变化
    hasChanges.value = JSON.stringify(newVal) !== JSON.stringify(originalData.value)
  },
  { deep: true }
)

// 保存设置
const handleSave = async () => {
  saving.value = true
  try {
    await saveSeoSettings(seoForm)
    originalData.value = { ...seoForm }
    showSuccessDialog.value = true
  } catch (error) {
    console.error('保存SEO设置失败:', error)
    alert('保存失败: ' + (error.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

// 放弃更改
const handleDiscardChanges = () => {
  Object.assign(seoForm, originalData.value)
  showDiscardConfirm.value = false
}

// 监听路由变化，有未保存的更改时提示
router.beforeEach((to, from, next) => {
  if (hasChanges.value && from.path === router.currentRoute.value.path) {
    showDiscardConfirm.value = true
    // 暂时存储导航目标，在确认后执行
    router.to = to
    next(false)
  } else {
    next()
  }
})

// 确认放弃后继续导航
watch(
  () => showDiscardConfirm.value,
  (newVal) => {
    if (!newVal && router.to) {
      router.push(router.to)
      router.to = null
    }
  }
)
</script>
